#include <QDebug>

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "common.h"
#include "input/inputdialog.h"
#include "Dialog/mymessagedialog.h"
#include "Setting/setting.h"
#include "Setting/BasicSetting/basicsettingwidget.h"
#include "Device/mashwelder.h"
#include "Device/PlasticPresses/plasticpresses.h"
#include "Device/PunchingMachine/punchingmachine.h"
#include "Setting/BasicSetting/basicsettingwidget.h"
#include "DataBase/databasequery.h"
#include "DataBase/dbtab_productionorder.h"

float inputvalue_float;
int inputvalue_int;
ProductionVariant  MainWindow::_productionVariant;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    mMainWidget(NULL),
    m_barcode("")
{
    ui->setupUi(this);
    startInit();
#ifdef QT_DEBUG
    this->setFixedSize(300,300);
#else
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
#endif
    this->setFixedSize(SCREEN_WIDTH,SCREEN_HIGH);
    //ui->statusBar->showMessage(tr("北京人民电器厂有限公司!"));
    initDeviceWidgetSelect();
    connect(mMainWidget,SIGNAL(openSettingSignal()),SLOT(openSetting()));
    ui->mainLayout->addWidget(mMainWidget);
    //ui->statusBar->setStyleSheet("background-color:#383a3c;color: rgb(243, 243, 243);");
    ui->statusBar->setVisible(false);
}



MainWindow::~MainWindow()
{
    delete ui;
}

MainWindow *MainWindow::mMainWindow = NULL;
MainWindow *MainWindow::getMainWindow()
{
    if(mMainWindow==NULL){
        mMainWindow = new MainWindow();
    }
    return mMainWindow;
}
void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::openSetting()
{
    Setting *set = new Setting(mMainWidget,ui->centralWidget->layout());
    set->cursor().setShape(Qt::WaitCursor);
    connect(set,SIGNAL(destroyed()),mMainWidget,SLOT(escFromSettings()));
}

void MainWindow::startInit() {

}

QLayout *MainWindow::mainLayout()
{
    return ui->mainLayout;
}

void MainWindow::initDeviceWidgetSelect()
{
    int mod = BasicSettingWidget::getOprtMode();
    switch (mod) {
    case BasicSettingWidget::MASHWELDER_MODE:
        mMainWidget =  new MashWelder(this);
        break;
    case BasicSettingWidget::PLASTIC_MODE:
        mMainWidget =  new PlasticPresses(this);
        break;
    case BasicSettingWidget::PUNCHING_MODE:
        mMainWidget =  new PunchingMachine(this);
        break;
    default:
        mMainWidget =  new MashWelder(this);
        break;
    }
}

void MainWindow::keyPressEvent(QKeyEvent *keyEvent)
{
    qDebug() << Q_FUNC_INFO;
    int key = keyEvent->key();
    QString code_text = keyEvent->text();
    if(key == Qt::Key_Return)
    {
        showBarcodeText(m_barcode);
        m_barcode.clear();
    }
    else {
        m_barcode+=code_text;
    }
}

void MainWindow::keyReleaseEvent(QKeyEvent *keyEvent)
{
    qDebug() << Q_FUNC_INFO;
    int key = keyEvent->key();
    static QString barcodeString = "";
    QString code_text = keyEvent->text();
    if(key == Qt::Key_Return)
    {
        showBarcodeText(barcodeString);
        barcodeString.clear();
    }
    else {
        barcodeString+=code_text;
    }
}

void MainWindow::showBarcodeText(  QString &barcodeText)
{
    qDebug() << Q_FUNC_INFO;
    ProductionVariant productinfo;
    mMainWidget->queryCurrentOrder(productinfo, mMainWidget->getCurrentTaskId());
    _productionVariant = productinfo;

    if(barcodeText.contains( QRegExp("^name")) )
    {
        QStringList userinfoList = barcodeText.trimmed().split(",");
        QString userName = "";
        QString userId = "";

        for(int i = 0; i < userinfoList.length(); i++)
        {
            if(i == 0)
            {
                QString user_name = userinfoList.at(i);
                userName = user_name.remove("name;");
            }
            if(i == 1)
            {
                QString temp = userinfoList.at(i);
                userId = temp.remove("userid;");
            }
        }

        QString strName  = userName.remove("name;");
        if(DeviceState::getObj()->getDeviceStation() == DeviceState::OPERATOR_WORK_STATION )
        {
            emit sendOperator(strName, userId,   DeviceState::OPERATOR_WORK_STATION  );
        }
        else if(DeviceState::getObj()->getDeviceStation() == DeviceState::QC_CHECK_STATION )
        {
            emit sendQC(strName, userId,   DeviceState::QC_CHECK_STATION  );
        }
        else if( DeviceState::FIRST_CHECK_STATION  ==  DeviceState::getObj()->getDeviceStation() )
        {
            emit sendFirstCheck(strName, userId,   DeviceState::FIRST_CHECK_STATION  );
        }
        else if(  DeviceState::MAINTAIN_STATION == DeviceState::getObj()->getDeviceStation()   )
        {
            emit sendMainTain(strName, userId,   DeviceState::MAINTAIN_STATION  );
        }

        QString station;
        mMainWidget->getDeviceStateObj()->getDeviceStationString(station);
        if (productinfo.TaskId.isEmpty() || station.isEmpty() ) {
//            return;
        }
        userId = userId.remove("userid;");
        mMainWidget->getHttpClientObj()->postGetUserInfo(userId,station,mMainWidget->getDeviceInfoObj()->deviceType,mMainWidget->getDeviceInfoObj()->deviceId,productinfo.TaskId);
    }
    else if(barcodeText.contains("TaskID",Qt::CaseInsensitive)  || barcodeText.contains("MCode",Qt::CaseInsensitive)   )
    {
        QStringList orderInfoList = barcodeText.trimmed().split(",");
        QString order = "";
        QString materialA  = "";
        for(int i = 0; i < orderInfoList.length(); i++)
        {
            if(i == 0) {
                QString order_temp = orderInfoList.at(i);
                order = order_temp.remove("Order:");
            }
            if(i == 1) {
                QString order_temp = orderInfoList.at(i);
                materialA = order_temp.remove("MCode:");
            }
        }
        order = order.remove("MName:");
        materialA = materialA.remove("MCode:");

        QJsonParseError jsonErr;
        QJsonDocument myjsonDoc1 = QJsonDocument::fromJson(productinfo.mbom_src.toLocal8Bit(),&jsonErr);
        if(jsonErr.error == QJsonParseError::NoError)
        {
            if(!myjsonDoc1.isEmpty())
            {
                if(myjsonDoc1.isArray())
                {
                    QJsonArray mbomArray = myjsonDoc1.array();
                    QJsonObject mbomSunObject;
                    QString projId = "";
                    QString mcode = "";
                    QString mnum = "";
                    static int judgeTime = 0;
                    static QString mcode_temp = "";

                    for (int i = 0; i < mbomArray.size(); i++)
                    {
                        mbomSunObject = mbomArray.at(i).toObject();
                        projId = mbomSunObject.value("ProjId").toString();
                        mcode = mbomSunObject.value("MCode").toString();
                        mnum = QString::number( mbomSunObject.value("Mnum").toInt(), 10);
                        if(mcode.trimmed().compare(materialA) == 0 && mcode_temp.trimmed().compare(materialA) != 0)
                        {
                            QString strorder = order.remove( "mname;");
                            QString strmaterialA = materialA.remove("mcode;");
                            QString strmnum =  mnum.remove("Mnum;");
                            barcodeText.clear();
                            emit sendMaterial( strmnum ,strorder, strmaterialA);//count name mcode
                            mcode_temp =  mcode;
                            judgeTime++;          
                            break;
                        }
                        else if(mcode.trimmed().compare(materialA) == 0 && mcode_temp.trimmed( ).compare(materialA) == 0)
                        {
                            MyMessageDialog::message(this,"警告！","物料重复！",1200);
                            break;
                        }
                    }

                    if (judgeTime == mbomArray.size())
                    {
                        mMainWidget->confirmMateral();
                        judgeTime = 0;
                        mcode_temp = "";
                    }
                    else if (judgeTime < mbomArray.size())
                    {
                        MyMessageDialog::message(this,
                                                 "警告！",
                                                 "正在扫描"+materialA +"\n请继续验证物料！已扫描通过"+QString::number(judgeTime, 10)+"个\n",
                                                 1200);
                    }
                }

            }
        }
    }
    else if(barcodeText.contains("tname",Qt::CaseInsensitive) )
    {
        QStringList strList =  barcodeText.split(",");
        QString strTName;
        QString strICode;
        for( int i =0; i < strList.size(); ++i )
        {
              if( 0==i )
              {
                 QString strTemp =  strList[i];
                 strTName = strTemp.remove("tname:");
              }
              if(i==1 )
              {
                 QString strTemp =  strList[i];
                 strICode = strTemp.remove("TCode:");
              }
        }
        QJsonDocument jsDoc =  QJsonDocument::fromJson( productinfo.ModuleId.toLocal8Bit().data());
        QString strTIcodeLocal = jsDoc.array().at(0).toObject().value( "ToolingCode" ).toString();
        if( strICode == strTIcodeLocal )
        {
            emit sendGongZhang(strTName, strICode );
            emit sig_GongZhuangOk();
        }
        else
        {
            MyMessageDialog::message(this,
                                     "警告！",
                                     "TCode不匹配, 扫描未通过",
                                     1200);
        }
    }
}
